 <template>
  <div class="autoBase">
    <div class="uploadBtn">
      <div class="tips" v-if="uploadStatus == 3">
        <el-alert title="上传成功" type="success" center description="您已成功上传文件" show-icon>
        </el-alert>
      </div>
      <div class="tips" v-if="uploadStatus == 2">
        <el-alert title="上传失败" type="error" description="请检查文件格式是否有误或者店铺类型是否一致" show-icon>
        </el-alert>
      </div>
      <el-upload :accept="['.csv']" :show-file-list="false" action="" :http-request="requestUpload" :headers="headers">
        <b class="button-n" v-if="uploadStatus == 1">上传表格</b>
        <b class="button-w" v-if="uploadStatus == 2 || uploadStatus == 3">重新上传</b>
      </el-upload>
    </div>
    <div class="filter" v-if="uploadStatus == 3">
      <p>填写需要发货的订单号或{{ shopType == 1 ? '淘宝' : shopType == 2 ? '天猫' : shopType == 3 ? '京东' :shopType == 4 ? '拼多多' : '其他店铺类型用户帐号' }}ID（买家账号）</p>
      <ul class="type">
        <li @click="check(item.value)" v-if="!(shopType==4&&item.value=='userId')" v-for="(item, index) in filteTypeArr" :key="index" :class="{ 'active': item.value == orderType }">
          <el-radio v-model="orderType" :label="item.value">{{ item.label }}</el-radio>
        </li>
      </ul>
      <div class="text">
        <div class="left">
          <el-input type="textarea" :rows="5" placeholder="请输入或复制您的信息，多条信息回车换行输入" v-model="filterText">
          </el-input>
          <br>
          <b class="text-button-b" @click="filterText=''">清空</b>
        </div>
        <div class="right">
          <img @click="lookImg" :src="operateImg" style="margin-left:12px;cursor:pointer;" width="200" height="200" alt="演示图">
        </div>
      </div>
      <div class="footer">
        <b class="button-n" @click="sureFilter">确认筛选</b>
      </div>
    </div>
    <div class="elAlert">
      <el-dialog custom-class="errorTip" title="筛选提示" :modal-append-to-body="false" :visible.sync="filterObj.show" width="440px" top="15vh">
        <p>未在表格中匹配到信息, 请您重新核实</p>
        <ul class="errorList">
          <li v-if="index < 3" v-for="(item, index) in filterObj.data.noMatchList" :key="index">{{ item }}</li>
          <li class="dot">
            <p v-if="filterObj.data.noMatchNum > 2">
              <i v-for="index in 3" :key="index"></i>
            </p>
            <span>共 {{ filterObj.data.noMatchNum }} 条</span>
          </li>
        </ul>
        <div class="footer">
          <!-- <b class="button-n" v-if="!isDown" @click="downFail">下载问题列表</b> -->
          <downCsv v-if="!isDown" :data="errorData" @downed="isDown=true"></downCsv>
          <b class="button-w" v-if="isDown" @click="backToEdit">返回修改</b>
        </div>
      </el-dialog>
      <el-dialog custom-class="errorTip" title="提示" :modal-append-to-body="false" :visible.sync="repeatObj.show" width="500px" top="15vh">
        <p>您的表格中有客户id信息重复, 请确认</p>
        <ul class="errorList">
          <li v-if="index < 3" v-for="(item, index) in repeatObj.data.duplicateList" :key="index">{{ item }}</li>
          <li class="dot">
            <p v-if="repeatObj.data.duplicateNum > 2">
              <i v-for="index in 3" :key="index"></i>
            </p>
            <span>共 {{ repeatObj.data.duplicateNum }} 条</span>
          </li>
        </ul>
        <div class="footer">
          <b class="button-n" @click="backFixed">有问题, 返回修改</b>
          <b class="button-w" @click="sureRepeat">没问题, 直接发货</b>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters, mapActions } from 'vuex'
import DownCsv from './downCsv'
export default {
  name: 'autoBase',
  components: {
    DownCsv
  },
  props: {
    shopType: {
      type: Number
    }
  },
  data () {
    return {
      orderType: 'userId',
      filterText: '', // 筛选填写的内容
      filteTypeArr: [
        {
          label: '买家帐号',
          value: 'userId'
        },
        {
          label: '订单号',
          value: 'orderId'
        }
      ],
      uploadStatus: 1, // 1 未上传状态, 2 上传失败状态, 3 上传成功状态
      filterObj: {
        show: false,
        data: ''
      },
      uploadFileName: '', // 上传文件并筛选后返回的文件名称
      isDown: false, // 是否已经下载失败列表
      filePostfix: '', // 上传的文件后缀类型
      errorData: [],
      repeatObj: { // 重复用户id
        show: false,
        data: []
      },
      operateImg: require('../../../../assets/images/operate.gif')
    }
  },
  computed: {
    headers () {
      return {
        accesstoken: this.userToken,
        userAccountId: this.userInfo.sellerAccountId
      }
    },
    idsArr: {
      get: function () {
        if (this.filterText) {
          let text = this.filterText.replace('.', '')
          text = text.replace(/'/g, '')
          text = text.replace(/ /g, '')
          text = text.replace(/^\n+/g, '')
          text = text.replace(/\n+$/g, '')
          text = text.replace(/\n+/g, '\n')
          text = text.split('\n')
          for (let i = 0; i < text.length; i++) {
            if (text[i] === '') {
              text.splice(i, 1)
            }
          }
          return text
        } else {
          return []
        }
      },
      set: function (val) {
        return val
      }
    },
    ...mapGetters([
      'userInfo',
      'userToken'
    ])
  },
  watch: {
    shopType (val) {
      if (val === 4) {
        this.orderType = 'orderId'
      } else {
        this.orderType = 'userId'
      }
    }
  },
  methods: {
    lookImg () {
      this.$lookImg.show(this.operateImg)
    },
    check (type) { // 选择筛选的填入内容类型
      this.orderType = type
    },
    backToEdit () {
      this.isDown = false
      this.filterObj.show = false
    },
    requestUpload (config) { // 自定义上传文件处理
      let file = config.file
      this.filePostfix = file.name.toLowerCase().substr(file.name.lastIndexOf('.'))
      if (this.filePostfix !== '.csv') { // 判断后缀格式不为.csv格式
        this.uploadStatus = 2
        this.$message({
          message: '请上传csv格式文件',
          type: 'error'
        })
      } else { // 文件后缀名为.csv 可以上传
        this.$message({
          message: '文件上传中, 请稍等!!!',
          type: 'warning',
          duration: 0,
          showClose: true
        })
        let fd = new FormData()
        fd.append('file', file)
        fd.append('oldFileName', file.name)
        fd.append('shopType', this.shopType)
        fd.append('sellerAccountId', this.userInfo.sellerAccountId)
        this.upload(fd)
      }
    },
    upload (fd) { // 开始上传文件
      this.$ajax.post('/file/task/uploadFile/smart', fd).then((res) => {
        this.$message.closeAll()
        if (res.data.code === '200') {
          this.uploadFileName = res.data.data.uploadFileName
          if (res.data.data.realNum === res.data.data.avilableNum) { // 表格解析成功数与实际数相等 才 算 成 功
            if (res.data.data.duplicateNum > 0) {
              this.repeatObj = {
                show: false,
                data: res.data.data
              }
            } else {
              this.repeatObj = {
                show: false,
                data: res.data.data
              }
            }
            this.uploadStatus = 3
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.uploadStatus = 2
            this.$message({
              message: '文件数据有误, 请检查后重新上传',
              type: 'error'
            })
          }
        } else if (res.data.code === '1001') { // 参数缺失, 表格未匹配到数据, 或上传文件店铺类型错误
          this.uploadStatus = 2
          this.$message({
            message: '上传的文件未匹配到对应参数, 请检查店铺类型是否一致',
            type: 'error'
          })
        } else {
          this.uploadStatus = 2
          this.$message({
            message: res.data.message,
            type: 'error'
          })
        }
      }).catch((err) => {
        console.error(err)
        if (err) {
          this.$message.closeAll()
          this.$message({
            message: '生意太火爆了, 请稍后再试',
            type: 'error'
          })
        }
      })
    },
    backFixed () { // 返回修改
      this.uploadStatus = 3
      this.repeatObj.show = false
    },
    sureRepeat () { // 确认无误
      this.uploadStatus = 3
      this.repeatObj.show = false
      this.uploadIds()
    },
    sureFilter () { // 点击确认筛选按钮开始筛选
      if (this.orderType === '') {
        this.$message({
          message: '请选择筛选类型',
          type: 'error'
        })
      } else if (this.filterText === '') {
        this.$message({
          message: '请填写筛选内容',
          type: 'error'
        })
      } else if (this.repeatObj.data.duplicateList.length > 0) {
        this.repeatObj.show = true
      } else {
        this.uploadIds()
      }
    },
    uploadIds () {
      this.$ajax.post('/file/task/uploadIds/', {
        uploadFileName: this.uploadFileName,
        shopType: this.shopType,
        sellerAccountId: this.userInfo.sellerAccountId,
        idType: this.orderType,
        ids: this.idsArr
      }).then((res) => {
        let saveData = res.data.data
        if (res.data.code === '200') {
          if (saveData.noMatchNum > 0) { // 有未匹配成功的
            this.filterObj = {
              show: true,
              data: saveData
            }
            this.downErrArr()
          } else { // 全部匹配成功  进入下一步
            if (saveData.productNames.length > 8) {
              this.$alert('请尽量控制sku在8个之内', '提示', {
                confirmButtonText: '确定'
                // callback: action => {
                //   this.$message({
                //     type: 'info',
                //     message: `action: ${action}`
                //   })
                // }
              })
            } else {
              saveData.shopType = this.shopType
              saveData.filePostfix = this.filePostfix.substring(1)
              this.setAutoTable(saveData)
              this.$router.push({ name: 'checkPackage', query: { tableType: 'autoTable' } })
            }
          }
        } else {
          this.$message({
            message: res.data.message,
            type: 'error'
          })
        }
      }).catch((err) => {
        if (err) {
          this.$message.closeAll()
          this.$message({
            message: '生意太火爆了, 请稍后再试',
            type: 'error'
          })
        }
      })
    },
    downErrArr () {
      let noMatchArr = this.filterObj.data.noMatchList
      let fillArr = this.idsArr
      let arr = []
      if (fillArr) {
        for (let i = 0; i < fillArr.length; i++) {
          let fillText = ''
          for (let j = 0; j < noMatchArr.length; j++) {
            if (noMatchArr[j] === fillArr[i]) {
              fillText = '未匹配'
            }
          }
          arr.push({
            err: fillText,
            fill: fillArr[i]
          })
        }
      }
      this.errorData = arr
    },
    downFail () {
      window.open(`/file/task/downloadErrorOrderIds?fileName=${this.uploadFileName}&shopType=${this.shopType}&filePostfix=csv`)
      setTimeout(() => {
        this.isDown = true
      }, 100)
    },
    ...mapActions([
      'setAutoTable'
    ])
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../../assets/stylus/index.styl'
.autoBase
  .uploadBtn
    text-align center
    margin-top 60px
    .tips
      width 400px
      margin 0 auto 20px
  .filter
    margin-top 20px
    p
      fontSize($fontSize-m, 1, $fontColor)
      margin-bottom 20px
    .type
      display flex
      margin-bottom 20px
      li
        height 40px
        line-height 40px
        padding 0 30px
        border 1px solid RGBA(136, 136, 136, 0.8)
        border-radius 2px
        text-align center
        cursor pointer
        margin-right 20px
        transition all 0.2s
      .active
        border 1px solid $fontColor-o
    .text
      display flex
      .left
        width 500px
      .right
        img
          max-width 500px
    .footer
      margin-top 40px
      text-align center
  .elAlert
    .errorTip
      p
        fontSize($fontSize-l, 1, fontColor)
        text-align center
      .errorList
        margin-top 24px
        text-align center
        li
          fontSize($fontSize-l, 1, $fontColor-o)
          margin-bottom 12px
        .dot
          fontSize($fontSize-l, 1, $fontColor-d)
          p
            display flex
            flex-direction column
            align-items center
            margin-bottom 12px
            i
              width 6px
              height 6px
              border-radius 50%
              background $fontColor-d
              margin-bottom 5px
      .footer
        text-align center
        margin-top 24px
</style>
